package com.igeek.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.igeek.entry.Item;
import com.igeek.service.ProService;



@Controller
public class ProController {

	@Autowired
	private ProService proService;
	@RequestMapping("showProList")
	public String  toProList(Map map) {
		List<Item> itemList = proService.findAll();
		map.put("itemList", itemList);
		return "proList";
	}

	@RequestMapping("alertPro")
	@ResponseBody
	public String selectPro(Integer id , Map map) {
		Item item =proService.findItemById(id);
		String  ssString =	JSON.toJSONString(item);
		return ssString;
	}

	@RequestMapping("updatePro")
	public String updatePro( MultipartFile pictureFile,Item item ,HttpServletRequest request) throws Exception{

		String oldName = pictureFile.getOriginalFilename();

		if(oldName!=null&&!oldName.equals("")) {
			String fString = UUID.randomUUID().toString();
			String fString2 = oldName.substring(oldName.lastIndexOf("."));
			String NewName = fString+fString2;
			String path= request.getServletContext().getRealPath("upload");
			File  file = new File(path,NewName);
			if (!file.exists()) {
				file.mkdir();
			}
			pictureFile.transferTo(file);
			item.setPic("upload/"+NewName);
		}
		if (item.getId() == null) {
			proService.inserPro(item);
		}else {
			proService.updateProByIdSelective(item);
		}

		return "redirect:showProList";
	}
	@RequestMapping("deletePro")
     public String deleteById(Integer id) {
		proService.deletePro(id);
		return "redirect:showProList";
	}
}
